<template>
  <div class='chatBody'>
    <mt-loadmore :top-method="loadTop" ref="loadmore" :style="bodyHeight" class="loadmoreBox" style="overflow: auto;-webkit-overflow-scrolling:touch;padding: 0.3rem 0.1rem 0.3rem 0.1rem;box-sizing:border-box;">
      <div class='chatBox'>
        <ul class='chat'>
          <li class='chatLi' v-for="(item,index) in websockList" :key="index"  :date="item.createTime">
            <p class='textC chatTime color5b5e5e' v-if="item.judge"><span class="timeBackground" v-if="$formatMsgTime(item.createTime)">{{$formatMsgTime(item.createTime)}}</span></p>
            <div style="padding:.16rem;">
              <div class='position-r' :class="[item.sendUserId == userId ? 'chatRight' : 'chatLeft']">
                <div class='flex-box'>
                  <img class='chatImg border-radius-50' :src="item.imagePath?item.imagePath:$defaultSetting.defaultPortrait"/>
                  <div class='flex-1 chatContent'>
                    <em class='chatContentJt'></em>
                    <span  class='text-align-j'>{{item.data}}</span>
                  </div>
                </div> 
              </div>
            </div>
          </li>
        </ul>
      </div>
      <div class="mint-loadmore-top" v-if="topStatus === 'loading'" style="color:#ccc;">
        <span v-if="topStatus === 'loading'" style="display: block;width: 30px;margin: 0 auto;"></span>
      </div>
    </mt-loadmore>
  </div>
</template>
<script>
import apiCircle from '../../api/circle'
import { Loadmore } from 'mint-ui'
window.Vue.component(Loadmore.name, Loadmore)

export default {
  data(){
      return{
          bodyHeight: 'height:'+document.body.clientHeight+'px',
          ws:'',
          data: '',
          topStatus: '',
          websockList:[],
          userId:this.$route.params.sendUserId,    //sendUserId为登陆人的id
          homeId:this.$route.params.recvUserId,    //recvUserId为与自己聊天人的id
          selfImgPath:'',
          count: 20,
          sendMessage: '',
          websocketJudge: true
      }
  },
  mounted(){
    window.sendValue = this.sendValue
    this.user(this.userId)
    this.websocket()
    this.chatArr(this.count)
  },
  methods:{
    // 查询个人信息
    user(queryId){
      apiCircle.userId({id:queryId}).then(data=>{
        if(data.body.returnMsg == 'success'){
          this.selfImgPath = data.body.data.list[0].imagePath
        }
      })
    },
    loadTop() {
      // 加载更多数据
      this.topStatus = 'loading'
      setTimeout(() => {
        this.count += 20
        this.chatArr(this.count)
      },1000)
      
    },
    // 查询聊天记录
    chatArr(count){
      let parmes = {sendUserId:this.homeId,recvUserId:this.userId,pageSize:count,pageNum:1},arrayChat=[]
      apiCircle.listChat(parmes).then(data=>{
        if(data.body.returnMsg == 'success'){
          data.body.data.list.forEach(element => {
            arrayChat.push(element)
          })
          this.websockList = arrayChat.reverse()
          for (var i = 0; i<this.websockList.length; i++) {
            this.websockList[i].data = this.websockList[i].message
            delete this.websockList[i].message
            var saveTime = this.websockList[i].createTime
            if (i == 0) {
                this.websockList[i].createTime = saveTime
                this.websockList[i].judge = true
            }
            if (i !== 0) {
              this.websockList[i].createTime = this.websockList[i].createTime
              if (this.websockList[i].createTime - this.websockList[i - 1].createTime  < 300000) {
                this.websockList[i].judge = false
              } else {
                this.websockList[i].judge = true
              }
            }
          }
          setTimeout(() => {
            this.TalkDown()
          },1)
        }
        this.$refs.loadmore.onTopLoaded();
        this.topStatus = ''
      })
    },
    //  发送消息
     sendValue(value) {
       if (this.websocketJudge) {
          if (value !== '') {
            var el = document.getElementsByTagName('li')
            if (!el.length) {
              var time = true
              var newTime = new Date().getTime()
            } else {
                var doc = el[el.length - 1].getAttribute('date')
                var newTime = new Date().getTime()
                if (newTime - doc > 300000) {
                  var time = true
                } else {
                  time = false
                }
            }
              let data = {
                  'data':value,
                  'imagePath':this.selfImgPath,
                  'sendUserId':this.userId,
                  'judge':time,
                  'createTime':newTime
                }
              this.ws.send(JSON.stringify(data))
          }
       } else {
         this.sendMessage = value
       }
    },
    // 聊天置底方法
    TalkDown () {
      var footer = document.getElementsByClassName('loadmoreBox')[0]
      footer.scrollTop = footer.scrollHeight
    },
    // 初始化websocket
    websocket () {
         this.ws = new WebSocket('ws://uat.ceiii.com.cn/common/chatRecordOneToOne/'+this.userId+'/'+this.homeId)
          this.ws.onopen = () => {
              console.log('连接成功...')
              this.websocketJudge = true
              this.sendValue(this.sendMessage)
          }
          this.ws.onmessage = evt => {
            if(evt.data != '连接成功'){
              this.websockList.push(JSON.parse(evt.data))
              setTimeout(() => {
                  this.TalkDown()
              },1)
            }
          }
          // 关闭 websocket
          this.ws.onclose = (evt) => {
            console.log(evt, '连接关闭')
            this.websocketJudge = false
            this.websocket()
          }
          window.onbeforeunload = (event) => {
            this.ws.close()
          }
    }
  }
}
</script>





